#!/usr/bin/env python
import sys
import time
import fitparse
import numpy
import lxml
from lxml import etree
from scipy import interpolate
import fittotcx

class HRMData:

  def __init__(self, filename):
    hr_data_started = False
    self.hrdata = []
    hrm = open(filename)
    for l in hrm.readlines():
      if hr_data_started:
        self.hrdata.append(int(l.split()[0]))
      elif l.startswith("[HRData]"):
        hr_data_started = True
      elif l.startswith("StartTime="):
        start_time_s = l.split("=")[1].strip()
      elif l.startswith("Date="):
        start_date_s = l.split("=")[1].strip()
      elif l.startswith("Interval="):
        self.interval = int(l.split("=")[1])

    self.start_time = time.strptime(
        start_date_s + " " + start_time_s,"%Y%m%d %H:%M:%S.%f")

    y = numpy.array(self.hrdata)
    x = numpy.linspace(0, len(self.hrdata), len(self.hrdata))
    f = interpolate.interp1d(x, y, kind='cubic')
    xnew = numpy.linspace(0, len(self.hrdata),
                          len(self.hrdata) * self.interval)
    self.end=f(xnew)

  def getPulseAt(self, moment):
    """Accepted string like 2011-07-10T13:21:48 """
    d_time = time.strptime(moment, "%Y-%m-%dT%H:%M:%S")
    offset = time.mktime(d_time) - time.mktime(self.start_time)
    return int(self.end[int(offset)])

hdata = HRMData(sys.argv[1])
tcx = etree.parse(open(sys.argv[2]))

for element in tcx.iter("{http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2}Time"):
  #print("%s - %s - %s" % (element.tag, element.text,
  #                        hdata.getPulseAt(element.text)))
  try:
    heart_rate = hdata.getPulseAt(element.text)
    parent = element.getparent()
    hr = fittotcx.createSubElement(parent, "HeartRateBpm")
    hr.set(fittotcx.XML_SCHEMA + "type", "HeartRateInBeatsPerMinute_t")
    fittotcx.createSubElement(hr, "Value", str(heart_rate))
  except:
    pass

print lxml.etree.tostring(tcx.getroot(), pretty_print=True, \
                              xml_declaration=True, encoding="UTF-8")
